package com.stable.actor.demo;

import com.stable.actor.core.ActorRef;
import com.stable.actor.core.StableActor;
import com.stable.actor.messages.MessageProtocol;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Client Actor - 模拟客户端行为
 */
public class ClientActor extends StableActor {
    private final String clientId;
    private final String clientType;
    private final AtomicInteger requestId = new AtomicInteger(0);
    private final AtomicInteger successCount = new AtomicInteger(0);
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
    private ActorRef master;

    public ClientActor(String clientId, String clientType) {
        this.clientId = clientId;
        this.clientType = clientType;
    }

    public void setMaster(ActorRef master) {
        this.master = master;
    }

    @Override
    protected void setupMessageHandlers() {
        receiveBuilder()
                .match(MessageProtocol.RegisterAck.class, this::handleRegisterAck)
                .match(MessageProtocol.WorkResponse.class, this::handleWorkResponse)
                .match(MessageProtocol.HeartbeatAck.class, this::handleHeartbeatAck)
                .match(String.class, this::handleStringMessage);
    }

    private void handleRegisterAck(MessageProtocol.RegisterAck ack) {
        System.out.println("🎉 " + clientId + " 注册成功: " + ack.message);

        // 注册成功后开始发送工作请求
        startSendingRequests();

        // 开始心跳
        startHeartbeat();
    }

    private void handleWorkResponse(MessageProtocol.WorkResponse response) {
        successCount.incrementAndGet();
        System.out.println("📥 " + clientId + " 收到响应: " + response.result +
                " [处理时间: " + response.processingTime + "ms]");
        System.out.println("✅ " + clientId + " 成功次数: " + successCount.get());
    }

    private void handleHeartbeatAck(MessageProtocol.HeartbeatAck ack) {
        System.out.println("💓 " + clientId + " 收到心跳确认 from " + ack.from);
    }

    private void handleStringMessage(String message) {
        System.out.println("📝 " + clientId + " 收到字符串: " + message);
    }

    private void startSendingRequests() {
        scheduler.scheduleAtFixedRate(() -> {
            if (master != null) {
                int currentId = requestId.incrementAndGet();
                String task = "任务#" + currentId + " from " + clientId;
                MessageProtocol.WorkRequest request = new MessageProtocol.WorkRequest(
                        clientId, currentId, task);

                master.tell(request, getSelf());
                System.out.println("📤 " + clientId + " 发送请求: " + currentId);
            }
        }, 2, 5, TimeUnit.SECONDS); // 2秒后开始，每5秒发送一次
    }

    private void startHeartbeat() {
        scheduler.scheduleAtFixedRate(() -> {
            if (master != null) {
                MessageProtocol.Heartbeat heartbeat = new MessageProtocol.Heartbeat(clientId);
                master.tell(heartbeat, getSelf());
                System.out.println("💗 " + clientId + " 发送心跳");
            }
        }, 10, 10, TimeUnit.SECONDS); // 10秒后开始，每10秒发送一次
    }

    @Override
    protected void preStart() {
        System.out.println("🎯 Client Actor启动: " + clientId);

        // 向Master注册
        if (master != null) {
            MessageProtocol.Register register = new MessageProtocol.Register(clientId, clientType);
            master.tell(register, getSelf());
            System.out.println("📝 " + clientId + " 发送注册请求");
        }
    }

    @Override
    protected void postStop() {
        scheduler.shutdown();
        System.out.println("🛑 Client Actor停止: " + clientId +
                ", 总成功: " + successCount.get());
    }
}
